package com.example.administrator.im;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.mob.MobSDK;

import org.litepal.LitePal;
import org.litepal.crud.LitePalSupport;

import java.util.Iterator;
import java.util.List;

/**
 * create:2018/9/13 23:08
 * author: 姚鸿杰
 **/
public class MyApplication extends Application {

    private static Context mContext;
    private static MyApplication app;
    private static final String TAG = "MyApplication";
    private int count = 0;

    public static Context getmContext() {
        return mContext;
    }

    public static MyApplication getApp() {
        return app;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        app = this;

        /**
         * Litepal初始化
         */
        LitePal.initialize(mContext);

        /**
         * mob初始化
         */
        MobSDK.init(this);


        /**
         * 环信配置
         */
        EMOptions options = new EMOptions();
        // 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
        // 是否自动将消息附件上传到环信服务器，默认为True是使用环信服务器上传下载，如果设为 false，需要开发者自己处理附件消息的上传和下载
        options.setAutoTransferMessageAttachments(true);
        // 是否自动下载附件类消息的缩略图等，默认为 true 这里和上边这个参数相关联
        options.setAutoDownloadThumbnail(true);

        //为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        // 如果APP启用了远程的service，此application:onCreate会被调用2次
        // 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
        // 默认的APP会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回
        if (processAppName == null || !processAppName.equalsIgnoreCase(mContext.getPackageName())) {
            Log.e(TAG, "enter the service process!");

            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }

        //初始化
        EMClient.getInstance().init(mContext, options);
        //在做打包混淆时，关闭debug模式，避免消耗不必要的资源
        EMClient.getInstance().setDebugMode(true);

        registerActivityLifecycleCallbacks(new mActivityLifecycle());
    }


    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    /**
     * 判断当前是否在后台
     *
     * @return 如果count = 0，表示在后台
     */
    public boolean getCountIsZero() {
        return count == 0;
    }

    private Activity mActivity;
    private Activity lastActivity;

    public Activity getmActivity() {
        return mActivity;
    }

    public Activity getLastActivity() {
        return lastActivity;
    }

    private class mActivityLifecycle implements ActivityLifecycleCallbacks {

        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {
        }

        @Override
        public void onActivityStarted(Activity activity) {
            if (count == 0) { //后台切换到前台
                Log.e(TAG, ">>>>>>>>>>>>>>>>>>>App切到前台");
            }
            count++;
        }

        @Override
        public void onActivityResumed(Activity activity) {
            if (mActivity == null) {
                lastActivity = activity;
            } else {
                lastActivity = mActivity;
            }
            mActivity = activity;
        }

        @Override
        public void onActivityPaused(Activity activity) {
        }

        @Override
        public void onActivityStopped(Activity activity) {
            count--;
            if (count == 0) { //前台切换到后台
                Log.e(TAG, ">>>>>>>>>>>>>>>>>>>App切到后台");
            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
        }
    }
}
